#include <stdio.h>
#include <setjmp.h>

#include "defs.h"
extern "C"{
#include "console.h"
#include "fxlib.h"
#define EXPR_BUF_SIZE 256

extern U ** mem;
extern unsigned int **free_stack;

int
initialize_tuamath()
{
	// modified by anderain 
	free_stack	= (unsigned int**)	calloc(500,sizeof(unsigned int*));
	mem			= (U**)				calloc(100,sizeof(U*));
	stack   	= (U**)				calloc(TOS,sizeof(U*));
	symtab  	= (U*)				calloc(NSYM,sizeof(U));
	binding 	= (U**)				calloc(NSYM,sizeof(U*));
	arglist 	= (U**)				calloc(NSYM,sizeof(U*));
	logbuf  	= (char*)			calloc(256,1);
}

const unsigned char *Setup[]={
	"logab(a,b)=log(b)/log(a)",
	"log10(x)=log(x)/log(10)",
	"ln(x)=log(x)",
	"cis(x)=cos(x)+i*sin(x)",
	"cot(x)=1/tan(x)",
	"coth(x)=cosh(x)/sinh(x)",
	"arccot(x)=arctan(1/x)",
	"arccoth(x)=arctanh(1/x)",
	"sec(x)=1/cos(x)",
	"sech(x)=1/cosh(x)",
	"arcsec(x)=arccos(1/x)",
	"arcsech(x)=arccosh(1/x)",
	"csc(x)=1/sin(x)",
	"csch(x)=1/sinh(x)",
	"arccsc(x)=arcsin(1/x)",
	"arccsch(x)=arcsinh(1/x)",
	"npr(n,r)=(n!)/(n-r)!",
	"ncr(n,r)=n!/(r!(n-r)!)",
	"xor(x,y)=or(and(x,not(y)),and(not(x),y))",
	NULL,
}

int AddIn_main(int isAppli, unsigned short OptionNum)
{
	unsigned int	key;
	unsigned char *expr;

	initialize_tuamath();
	// initialize failed ?
	if (!(free_stack && mem && stack && symtab && binding && arglist && logbuf))
		return 0;

	int i = 0;
	while(Setup[i] != NULL)
	{
		run((char *)Setup[i++]);
	}

    Console_Init();
	Console_Disp();
	while(1)
	{
		if((expr=Console_GetLine())==NULL) stop("memory error");
		run((char *)expr);
		Console_NewLine(LINE_TYPE_OUTPUT,1);
		Console_Disp();
	}


	for(;;)GetKey(&key);
    return 1;
}

#pragma section _BR_Size
unsigned long BR_Size;
#pragma section

#pragma section _TOP
int InitializeSystem(int isAppli, unsigned short OptionNum)
{
    return INIT_ADDIN_APPLICATION(isAppli, OptionNum);
}
#pragma section

}